package lookas.foto;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import lookas.track.GPSPosition;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.lang.CompoundException;
import com.drew.metadata.Directory;
import com.drew.metadata.exif.ExifDirectory;

public class FotoPosition extends GPSPosition{

    private File foto;

    public FotoPosition(File foto, long timedelta) throws CompoundException{
        this.foto = foto;
        this.date = new Date(FotoPosition.readDate(foto).getTime() + timedelta);
    }

    @Override
    public String toString(){
        return foto.getName() + ": " + super.toString();
    }

    @Override
    public String toXML(){
        try{
            return toXML(null);
        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }

    public String toXML(String parent) throws IOException{
        String ret;
        String path;
        if(parent == null)
            path = foto.getCanonicalPath();
        else
            path = parent + foto.getName();
        ret = String.format("<foto date=\"%s\" src=\"%s\">",
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .format(this.getDate()), path);
        ret += position.toXML();
        ret += "</foto>";
        return ret;
    }

    public static Date readDate(File foto) throws CompoundException{
        Directory directory = JpegMetadataReader.readMetadata(foto)
            .getDirectory(ExifDirectory.class);
        return directory.getDate(ExifDirectory.TAG_DATETIME_ORIGINAL);
    }
}
